from grid_env_ideal_obs_repeat_task import *
from grid_agent import *
from checkpoint_utils import *
from maze_factory import *
from replay_config import *
import argparse
import json
import sys
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
import random
from sklearn.decomposition import PCA
from matplotlib.animation import FuncAnimation
from sklearn.cluster import KMeans
import threading
import mplcursors
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

def progress_bar(current, total, barLength = 100):
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * barLength - 1) + '>'
    spaces = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
    sys.stdout.flush()

@partial(jax.jit, static_argnums=(3,))
def model_forward(variables, state, x, model):
    """ forward pass of the model
    """
    return model.apply(variables, state, x)

@jit
def get_action(y):
    return jnp.argmax(y)
get_action_vmap = jax.vmap(get_action)

# load landscape and states from file
def load_task(pth = "./logs/task.json", display = True):
    # open json file
    with open(pth, "r") as f:
        data = json.load(f)
        landscape = data["data"]
        state = data["state"]
        goal = data["goal"]
        if display:
            print("state: ", state)
            print("goal: ", goal)
            print("landscape: ", landscape)
    return landscape, state, goal


def get_intrinsic_pc():

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)
    parser.add_argument("--start_i", type=int, default=rpl_config.start_i)
    parser.add_argument("--end_i", type=int, default=rpl_config.end_i)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration
    rpl_config.start_i = args.start_i
    rpl_config.end_i = args.end_i

    """ load model
    """
    params = load_weights(rpl_config.model_pth)

    # get elements of params
    tree_leaves = jax.tree_util.tree_leaves(params)
    for i in range(len(tree_leaves)):
        print("shape of leaf ", i, ": ", tree_leaves[i].shape)
    
    """ create agent
    """
    if rpl_config.nn_type == "vanilla":
        model = RNN(hidden_dims = rpl_config.nn_size)
    elif rpl_config.nn_type == "gru":
        model = GRU(hidden_dims = rpl_config.nn_size)

    # check if param fits the agent
    if rpl_config.nn_type == "vanilla":
        assert params["params"]["Dense_0"]["kernel"].shape[0] == rpl_config.nn_size + 10

    n_samples = 1000
    k1 = npr.randint(0, 1000000)
    rnn_state = model.initial_state_rnd(n_samples, k1)
    rnn_state_old = rnn_state.copy()
    diff = jnp.abs(rnn_state - rnn_state_old)
    rnn_state_old = rnn_state.copy()
    diff_norm = jnp.linalg.norm(diff, axis=1)
    diff_norm_old = diff_norm.copy()
    norm_std = diff_norm.copy()

    rnn_state_init = rnn_state.copy()

    obs_zero = jnp.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(n_samples)])

    rnn_state_trajectory = []

    for t in range(rpl_config.life_duration):

        if t == rpl_config.probe_point:
            rnn_state_init = rnn_state.copy()

        progress_bar(t, rpl_config.life_duration)

        """ model forward 
        """
        rnn_state, y1 = model_forward(params, rnn_state, obs_zero, model)
        diff = jnp.abs(rnn_state - rnn_state_old)
        rnn_state_old = rnn_state.copy()
        diff_norm = jnp.linalg.norm(diff, axis=1)
        norm_std = 0.4 * jnp.abs(diff_norm - diff_norm_old) + 0.6 * norm_std
        diff_norm_old = diff_norm.copy()

        rnn_state_trajectory.append(np.array(rnn_state).copy())
            
    print(rnn_state.shape)
    print(norm_std.shape)
    rnn_state_np = np.array(rnn_state)

    # 将 rnn_state_trajectory 展开成 rnn_state_np 的形状
    rnn_state_trajectory_np = np.array(rnn_state_trajectory)
    rnn_state_trajectory_np = rnn_state_trajectory_np.reshape(-1, rnn_state_trajectory_np.shape[-1])
    print("shape of rnn_state_trajectory_np: ", rnn_state_trajectory_np.shape)

    # 对 rnn_state_np 进行 PCA
    pca = PCA()
    # pca.fit(rnn_state_np)
    pca.fit(rnn_state_trajectory_np)

    # 打印 variance ratio
    print(pca.explained_variance_ratio_)

    rnn_state_np_pca = pca.transform(rnn_state_np)

    # 创建KMeans对象，指定聚类数为4
    kmeans = KMeans(n_clusters=4)
    # 对rnn_state_np_pca进行聚类
    kmeans.fit(rnn_state_np_pca)
    # 获取聚类中心的坐标
    cluster_centers = kmeans.cluster_centers_

    return pca, cluster_centers


def main():

    intrinsic_pca, cluster_centers = get_intrinsic_pc()

    seq_len = 5
    n_samples = 10

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration

    """ load model
    """
    params = load_weights(rpl_config.model_pth)

    
    arrow_length = 1
    arrow_list = np.array([[arrow_length, 0], [-arrow_length, 0], [0, arrow_length], [0, -arrow_length], [0, 0]])

    # 生成一个二进制串集合，其中每个元素都是一个长度为8的二进制串，要求这些二进制串从 000000000 遍历到 111111111
    binary_set = set()
    for i in range(256):
        binary_string = format(i, '08b')
        binary_set.add(binary_string)
    # 将 binary_set 中的 11111111 元素删除
    binary_set.remove("11111111")
    # 将 binary_set 中所有格式为 "x1x1x1x1" 的元素删除
    binary_set_bk = binary_set.copy()
    for binary in binary_set_bk:
        if binary[1] == '1' and binary[3] == '1' and binary[4] == '1' and binary[6] == '1':
            binary_set.remove(binary)
    print("binary_set: ", binary_set)
    
    # 对 binary_set 进行排序，使得其中的元素从 00000000 遍历到 11111110
    binary_list = sorted(binary_set)
    # 将 binary_list 中的每个元素进行这样的操作：在中间插入一个0，例如 "00000000" 转换为 "000000000"；然后在结尾处插入一个0，例如 "000000000" 转换为 "0000000000"
    binary_list = [i[:4] + "0" + i[4:] + "0" for i in binary_list]
    # 将 binary_list 中的元素转换为整数数组，例如 "00000000" 转换为 [0, 0, 0, 0, 0, 0, 0, 0]
    binary_list = [list(map(int, list(i))) for i in binary_list]
    binary_list = np.array(binary_list)
    print("shape of binary_list: ", binary_list.shape)

    binary_list, arrow_list = jnp.array(binary_list), jnp.array(arrow_list)

    def make_obs_img(obs_int):
        # 将形状为 (10,) 的 obs 裁减掉最后一位，变成形状为 (9,) 的 obs
        obs = obs_int[:-1]
        # 将 obs 转换为形状为 (3, 3) 的 numpy 数组
        obs = obs.reshape((3, 3))
        
        # 将 obs 中的 1 替换为 255
        obs = (1-obs) * 255
        # 将 obs 转换为形状为 (3, 3, 1) 的 numpy 数组
        obs = obs.reshape((3, 3, 1))
        # 将 obs 转换为形状为 (3, 3, 3) 的 numpy 数组
        obs = np.concatenate((obs, obs, obs), axis=2)
        # 将 obs 转换为 opencv 的8比特图像格式
        obs = obs.astype(np.uint8)
        # 将 obs 转换为形状为 (60, 60, 3) 的 numpy 数组
        obs = cv2.resize(obs, (60, 60), interpolation=cv2.INTER_NEAREST)
        # 在 obs 上绘制 3x3 的灰色网格
        for i in range(1, 3):
            cv2.line(obs, (0, i*20), (60, i*20), (100, 100, 100), 1)
            cv2.line(obs, (i*20, 0), (i*20, 60), (100, 100, 100), 1)
        # 在 obs 的边缘绘制灰色边框
        cv2.rectangle(obs, (0, 0), (59, 59), (100, 100, 100), 1)
        return obs

    # 设置随机种子为10
    # np.random.seed(10)
    # 生成长度为20的随机整数序列，其中每个数字都在 0-239 之间，且不重复
    random_integers = np.random.choice(240, seq_len, replace=False)
    # random_integers = np.array([219 for i in range(seq_len)])

    random_obs_choosen = binary_list[random_integers]
    random_obs_choosen_img = []
    for i in range(seq_len):
        random_obs_choosen_img.append(make_obs_img(random_obs_choosen[i]))
    # 将 random_obs_choosen_img 全部水平拼接成一张大图
    random_obs_choosen_img = np.concatenate(random_obs_choosen_img, axis=1)
    cv2.imshow("random_obs_choosen_img", random_obs_choosen_img)
    cv2.waitKey(0)

    print("random_integers : ", random_integers)

    # get elements of params
    tree_leaves = jax.tree_util.tree_leaves(params)
    for i in range(len(tree_leaves)):
        print("shape of leaf ", i, ": ", tree_leaves[i].shape)
    
    """ create agent
    """
    if rpl_config.nn_type == "vanilla":
        model = RNN(hidden_dims = rpl_config.nn_size)
    elif rpl_config.nn_type == "gru":
        model = GRU(hidden_dims = rpl_config.nn_size)

    # check if param fits the agent
    if rpl_config.nn_type == "vanilla":
        assert params["params"]["Dense_0"]["kernel"].shape[0] == rpl_config.nn_size + 10

    k1 = npr.randint(0, 1000000)
    rnn_state = model.initial_state_rnd(n_samples, k1)
    # rnn_state = model.initial_state(n_samples)
    rnn_state_old = rnn_state.copy()
    diff = jnp.abs(rnn_state - rnn_state_old)
    rnn_state_old = rnn_state.copy()
    diff_norm = jnp.linalg.norm(diff, axis=1)
    diff_norm_old = diff_norm.copy()
    norm_std = diff_norm.copy()

    rnn_state_initial = rnn_state.copy()

    obs_zero = jnp.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(n_samples)])

    rnn_state_trajectory = []
    actions_trajectory = []

    random_integers_i = 0
    def update_random_integers_i():
        nonlocal random_integers_i
        nonlocal seq_len
        random_integers_i += 1
        random_integers_i %= seq_len

    for t in range(rpl_config.life_duration):

        if t == rpl_config.probe_point:
            rnn_state_init = rnn_state.copy()

        progress_bar(t, rpl_config.life_duration)

        random_obs = binary_list[random_integers[random_integers_i]]
        obs_zero = jnp.array([random_obs for i in range(n_samples)])

        """ model forward 
        """
        rnn_state, y1 = model_forward(params, rnn_state, obs_zero, model)
        actions = get_action_vmap(y1)
        
        rnn_state_trajectory.append(np.array(rnn_state).copy())
        actions_trajectory.append(np.array(actions).copy())
        update_random_integers_i()

    rnn_state_trajectory_np = np.array(rnn_state_trajectory)
    # 交换 rnn_state_trajectory_np 的第一维和第二维
    rnn_state_trajectory_np = np.swapaxes(rnn_state_trajectory_np, 0, 1)
    print("shape of rnn_state_trajectory_np: ", rnn_state_trajectory_np.shape)

    actions_trajectory_np = np.array(actions_trajectory)
    actions_trajectory_np = np.swapaxes(actions_trajectory_np, 0, 1)
    print("shape of actions_trajectory_np: ", actions_trajectory_np.shape)

    # print(actions_trajectory_np[0,-100:])

    # 将 rnn_state_np_pca 的前三维用 plot 进行可视化
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    rnn_state_initial_pca = intrinsic_pca.transform(rnn_state_initial)
    # 用红色圆点表示 rnn_state_initial_pca 的位置
    ax.scatter(rnn_state_initial_pca[:, 0], rnn_state_initial_pca[:, 1], rnn_state_initial_pca[:, 2], c='r', marker='o')

    for k in range(rnn_state_trajectory_np.shape[0]):

        rnn_state_np_pca = intrinsic_pca.transform(rnn_state_trajectory_np[k])

        # 绘制成线段连线, 并且按照时间顺序赋予其透明度，时间越早，透明度越低
        for i in range(rnn_state_np_pca.shape[0] - 1):
            ax.plot(rnn_state_np_pca[i:i+2, 0], rnn_state_np_pca[i:i+2, 1], rnn_state_np_pca[i:i+2, 2], c='b',
                    alpha=min(i/rnn_state_np_pca.shape[0]+0.1, 1.0))
        # ax.plot(rnn_state_np_pca[:, 0], rnn_state_np_pca[:, 1], rnn_state_np_pca[:, 2], c='b', alpha=0.01)

    plt.show()

    # 模仿上面的可视化流程，将 actions_trajectory_np 作为多个一维序列进行 plot 可视化，绘制成2D 折线图
    fig, ax = plt.subplots()
    for k in range(actions_trajectory_np.shape[0]):
        ax.plot(actions_trajectory_np[k], c='b', alpha=0.1)
    plt.show()
    



if __name__ == "__main__":
    main()